#!/usr/bin/python

import socket
import os, sys
import getpass

HOST = "" # localhost
PORT = 6666  # port

iGIS = '/home/' + getpass.getuser() + '/iGIS/'

try:
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect((HOST, PORT))
  sock.send('hello serv!')
  result = sock.recv(16)

  if not result == 'hello client!':
    print 'greeting - FAIL'
    sys.exit()
  else:
    print 'OK - hello'
    
  sock.send('listmap')
  serverMaps = sock.recv(1024).split()  #list of md5sums *.gis

  # no need of check - each server has 1 map at least
  # if len(result) < 10:
  #   print 'list of maps from server is empty'

  # check the folder /home/username/iGIS
  # compare all filenames with names in result
  # find ones that we don't have

  ls_iGIS = os.listdir(iGIS)

  serverMapsDict = {}  # need list because of specific server tasks
  n = 0
  while 1:
    if n > len(serverMaps) - 2:
      break
    number, name = serverMaps[n], serverMaps[n+1]
    serverMapsDict[number] = name
    n += 2

  print 'server maps : ', serverMapsDict

  missedMaps = {}  # missed maps 
  for mapNum, mapName in serverMapsDict.iteritems():
    if mapName not in ls_iGIS:
      missedMaps[mapName] = mapNum

  print 'missed maps : ', missedMaps

  # request of maps
  if len(missedMaps) > 0:
    for mapName, mapNum in missedMaps.iteritems():
      sock.send('get ' + mapNum)
      result = sock.recv(10240)  # bufsize can be higher
      if result:
        mapfile = open(iGIS + '/' + mapName, 'wb')
        mapfile.write(result)
        mapfile.close()
        del result
        print 'OK - received map ' + mapName

  sock.send('goodbye serv!')
  print 'closing connection with server...'
  result = sock.recv(4)
  if result == 'goodbye client':
    sock.close()
  print 'OK - closed'
    
except Exception:
  print 'can not connect to the server'
  sock.close()
  
